import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:intl/intl.dart' hide TextDirection;

import 'timeline_model.dart';

class TimeLinePainter extends RenderBox {
  double _contentWidth;
  double _visibleWidth;
  double _height;
  void Function(bool, TimeLineModel?)? _callBack;


  // 滑动偏移量（X轴方向）
  double _offsetX = 0;

  // 触摸起始位置
  double? _startTouchX;

  // 滑动开始时的偏移量
  double? _startOffsetX;

  DateTime _startDateTime;
  DateTime _endDateTime;
  /// 24 整屏宽度表示 24 小时
  /// 12 整屏宽度表示 12 小时
  /// 6 整屏宽度表示 6 小时
  int _timeType;

  List<TimeLineModel> _timeLines;

  TimeLinePainter({
    required DateTime startDateTime,
    required DateTime endDateTime,
    required int timeType,
    required List<TimeLineModel> timeLines,
    required double contentWidth,
    required double visibleWidth,
    required double height,
    required void Function(bool, TimeLineModel?)? callBack,
  }) : _contentWidth = contentWidth,
       _visibleWidth = visibleWidth,
        _startDateTime = startDateTime,
        _endDateTime = endDateTime,
        _timeType = timeType,
        _timeLines = timeLines,
       _height = height,
       _callBack = callBack {
        _offsetX = _getInitOffset(visibleWidth,timeType,startDateTime,endDateTime);
}


  double _getInitOffset(double visibleWidth,int timeType,DateTime startTime,DateTime endTime) {
    _perSecondPixel = visibleWidth / (timeType * 60 * 60);
    int diff = ((endTime.millisecondsSinceEpoch - startTime.millisecondsSinceEpoch) / 1000).toInt();
    return diff * _perSecondPixel - visibleWidth;
  }
  
  set startTime(DateTime value) {
    if(!_startDateTime.isAtSameMomentAs(value)) {
      _startDateTime = value;
      _clampOffset();
      markNeedsPaint();
    }
  }

  set endTime(DateTime value) {
    if(!_endDateTime.isAtSameMomentAs(value)) {
      _endDateTime = value;
      _clampOffset();
      markNeedsPaint();
    }
  }

  set timeType(int value) {
    if(_timeType != value) {
      _timeType = value;
      _clampOffset();
      markNeedsPaint();

    }
  }

  set timeLines(List<TimeLineModel> values) {
    if(_timeLines != values) {
      _timeLines = values;
      _clampOffset();
      markNeedsPaint();
    }
  }

  // 设置属性的setter（触发重绘/重布局）
  set contentWidth(double value) {
    if (_contentWidth != value) {
      _contentWidth = value;
      _clampOffset(); // 确保偏移量在有效范围
      markNeedsPaint();
    }
  }

  set visibleWidth(double value) {
    if (_visibleWidth != value) {
      _visibleWidth = value;
      _clampOffset();
      markNeedsPaint();
    }
  }

  set height(double value) {
    if (_height != value) {
      _height = value;
      markNeedsPaint();
    }
  }

  set callBack(void Function(bool, TimeLineModel?)? value) {
    _callBack = value;
    markNeedsPaint();
  }

  // 限制偏移量范围（防止滑出边界）
  void _clampOffset() {
    final maxOffset = _contentWidth - _visibleWidth;
    _offsetX = _offsetX.clamp(0.0, maxOffset);
  }

  // 处理触摸事件
  @override
  bool hitTestSelf(Offset position) => true; // 自身响应触摸


  var startMills = 0;
  var endMills = 0;

  @override
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
    super.handleEvent(event, entry);

    if (event is PointerDownEvent) {
      print("PointerDownEvent");
      startMills = DateTime.now().millisecondsSinceEpoch;
      // 记录触摸起始位置
      _startTouchX = event.localPosition.dx;
      _startOffsetX = _offsetX;
    } else if (event is PointerMoveEvent &&
        _startTouchX != null &&
        _startOffsetX != null) {
      print("PointerMoveEvent");
      endMills = DateTime.now().millisecondsSinceEpoch;
      print("111111111 ${endMills - startMills}");
      // 计算滑动偏移（手指移动距离 = 当前位置 - 起始位置）
      final deltaX = event.localPosition.dx - _startTouchX!;
      print("111111111 delta ${deltaX}");
      if(deltaX != 0.0) {
        _offsetX = _startOffsetX! - deltaX; // 负号表示反向滑动（手指右滑内容左移）
        _clampOffset(); // 限制边界
        markNeedsPaint(); // 触发重绘
      }
    } else if (event is PointerUpEvent || event is PointerCancelEvent) {
      print("PointerUpEvent");
      endMills = DateTime.now().millisecondsSinceEpoch;
      print("222222 ${endMills - startMills}");
      // 触摸结束，清理状态
      _startTouchX = null;
      _startOffsetX = null;
    }
  }

  // 布局逻辑（设置组件大小）
  @override
  void performLayout() {
    size = Size(_visibleWidth, _height);
  }

  bool isCanvas = false;

  // 绘制逻辑
  @override
  void paint(PaintingContext context, Offset offset) {
    final canvas = context.canvas;
    //final contentSize = Size(_contentWidth, _height);

    ///屏幕宽度减去圆形宽度和标尺柱子高度
    /// 保存画布状态
    canvas.save();

    /// 1. 裁剪可视区域（超出部分不绘制）
    canvas.clipRect(offset & size);
    /// 2. 平移画布（实现滑动效果）
    canvas.translate(offset.dx - _offsetX, offset.dy);

    /// 3. 绘制时间标尺
    drawRules(canvas);

    drawTimeline(canvas);

    /// 恢复画布状态
    canvas.restore();

    //计算屏幕中间位置
    calRulePosition();

  }

  final Paint _ruleCirclePaint = Paint()..color = const Color(0x4C1B1B2E);

  final Paint _ruleBarPaint = Paint()..color = const Color(0x4C1B1B2E);

  //柱子宽度
  final _ruleBarWidth = 2.0;
  //柱子高度
  final _ruleBarHeight = 4.0;
  //圆半径
  final _ruleCircleRadius = 2.0;

  double _ruleInterval = 0;

  double startOffset = 15;

  double timeOffset = 13;

  //每秒所占的像素位
  double _perSecondPixel = 0;

  int circleCount = 4;
  int barCount = 20;

  //
  void drawRules(Canvas canvas) {

    if(_timeType == 24) {
      circleCount = 4;
      barCount = 20;
    } else if(_timeType == 12) {
      circleCount = 2;
      barCount = 10;
    } else  if(_timeType == 6) {
      circleCount = 1;
      barCount = 5;
    }

    _ruleInterval =  ( _visibleWidth -  circleCount * _ruleCircleRadius * 2 - barCount * 2) / _timeType;
    _perSecondPixel = _visibleWidth / (_timeType * 60 * 60);

    double offset = _ruleInterval + 2;
    var diffSecond = ((_endDateTime.millisecondsSinceEpoch - _startDateTime.millisecondsSinceEpoch) / 1000).toInt();
    int dayCount = (diffSecond / (24 * 60 * 60)).ceil();
    //天数
    for(int day = 0; day < dayCount; day ++) {
      //每天 24 小时
      for (int i = 0; i < 24; i++) {
        if (i % 6 == 0) {
          canvas.drawCircle(
              Offset(offset + _ruleCircleRadius, _height - 20 - _ruleCircleRadius),
              _ruleCircleRadius, _ruleCirclePaint);
          String timeText = "";
          if(i / 6 == 0) {
            timeText = "12 AM";
          } else if(i / 6 == 1) {
            timeText = "06 AM";
          }else if(i / 6 == 2) {
            timeText = "12 PM";
          }else if(i / 6 == 3) {
            timeText = "06 PM";
          }
          TextPainter tp = TextPainter(text: TextSpan(
              text: timeText, style: TextStyle(color: Colors.red, fontSize: 10)),
              textDirection: TextDirection.ltr);
          tp.layout();
          tp.paint(canvas, Offset(offset - timeOffset, _height - 15));
          offset = offset + _ruleCircleRadius * 2 + _ruleInterval;
        } else {
          RRect rect = RRect.fromLTRBAndCorners(
            offset,
              _height - _ruleBarHeight - 20,
            offset + _ruleBarWidth,
            _height - 20,
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
            bottomLeft: Radius.circular(12),
            bottomRight: Radius.circular(12),
          );
          canvas.drawRRect(rect, _ruleBarPaint);

          offset = offset + _ruleBarWidth + _ruleInterval;
        }
      }
    }
    _contentWidth = offset;
    // print("visibleWidth $_visibleWidth");
    // print("contentWidth $_contentWidth");
  }

  //时间轴高度
  double timeLineHeight = 12;
  //时间轴距离底部高度
  double timeLineToBottomDistance = 50;

  void drawTimeline(Canvas canvas) {

    startOffset = _ruleInterval + 2;

    for(int i = 0; i < _timeLines.length; i ++) {
      TimeLineModel model = _timeLines[i];
      double start = ((model.startTime.millisecondsSinceEpoch - _startDateTime.millisecondsSinceEpoch) / 1000) * _perSecondPixel;
      double end = ((model.endTime.millisecondsSinceEpoch - _startDateTime.millisecondsSinceEpoch) / 1000) * _perSecondPixel;

      RRect rect = RRect.fromLTRBAndCorners(
        startOffset + start,
        _height - timeLineHeight - timeLineToBottomDistance,
        startOffset + end,
        _height - 50,
        topLeft: Radius.circular(4),
        topRight: Radius.circular(4),
        bottomLeft: Radius.circular(4),
        bottomRight: Radius.circular(4),
      );
      canvas.drawRRect(rect, _ruleBarPaint);

    }

  }

  final dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");

  void calRulePosition() {
    ///计算屏幕中间位置的时间
    ///先计算前面有多少天
    double days  =  (_offsetX / _visibleWidth);
    int duration = (days * _timeType * 60 * 60).round() + (_timeType / 2).toInt() * 60 * 60;
    //减去起始位置的占位
    duration = duration - 1 * 60 * 60;
    // int hours = (duration ~/ 3600);
    // int minutes = (duration ~/ 60) % 60;
    // int seconds = duration % 60;
    ///print("time: hour $hours minute $minutes  second $seconds");
    //当前日期
    int mills = _startDateTime.millisecondsSinceEpoch + duration * 1000;
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(mills);
    print(dateFormat.format(dateTime));

    //是否命中目标
    for (var model in _timeLines) {
      var startMills = model.startTime.millisecondsSinceEpoch;
      var endMills = model.endTime.millisecondsSinceEpoch;
      if(startMills <= mills && mills <= endMills) {
        _callBack?.call(true, model);
        return;
      }
    }
    _callBack?.call(false, null);


  }

  // 优化重绘性能
  @override
  bool get isRepaintBoundary => true;
}
